﻿using System;
using System.Collections.Generic;
using System.Text;

namespace LNet
{

    //接收到的数据转换为字节数组
    public class Message
    {
        //存储接收到的数据
        private byte[] data = new byte[1024];
        private int startIndex = 0;//存储位置的开始索引，也表示已存储数据的长度

        public byte[] Data
        {
            get { return data; }
        }
        public int StartIndex
        {
            get { return startIndex; }
        }

        //闲置空间长度
        public int RemainSize
        {
            get { return data.Length - startIndex; }
        }
        public void ParseFromClientMessage(int newDataLength, Action<Request> processDataCallback)
        {
            startIndex += newDataLength;
            while (true)
            {
                if (startIndex <= 4) return;
                //需要处理数据的长度
                int count = BitConverter.ToInt32(data, 0);
                if ((startIndex - 4) >= count)
                {
                    Request request = new Request()
                    {
                        RequestCode = (PacketKey)BitConverter.ToInt32(data, 4),
                        RequestSubCode = (SubCode)BitConverter.ToInt32(data, 8)
                    };
                    int recieveIDsLenth = BitConverter.ToInt32(data, 12);//接收ID集序列字符串所占字节长度

                    string strRecieveIDs = Encoding.UTF8.GetString(data, 16, recieveIDsLenth);
                    List<int> recieveIDs = LitJson.JsonMapper.ToObject<List<int>>(strRecieveIDs);

                    string dataStr = Encoding.UTF8.GetString(data, 16 + recieveIDsLenth, count - 12 - recieveIDsLenth);
                    request.DataObject = dataStr;
                    processDataCallback(request);
                    Array.Copy(data, count + 4, data, 0, startIndex - 4 - count);
                    startIndex -= (count + 4);
                }
                else
                {
                    break;
                }
            }
            ReSize();//处理完数据后重置缓存区
        }


        /// <summary>
        /// 解析从服务器来的数据
        /// </summary>
        public void ParseFromServerMessage(int newDataLength, Action<Response> processDataCallback)
        {
            startIndex += newDataLength;
            while (true)
            {
                if (startIndex <= 4) return;
                //需要处理数据的长度
                int count = BitConverter.ToInt32(data, 0);
                if ((startIndex - 4) >= count)
                {
                    Response p = new Response()
                    {
                        ResponseCode = (PacketKey)BitConverter.ToInt32(data, 4),
                        ResponseSubCode = (SubCode)BitConverter.ToInt32(data, 8),
                        ReturnCode = (ReturnCode)BitConverter.ToInt32(data, 12),
                        RequestClientID = BitConverter.ToInt32(data, 16)
                    };

                    int recieveIDsLength = BitConverter.ToInt32(data, 20);

                    string strIDs = Encoding.UTF8.GetString(data, 24, recieveIDsLength);
                    if (String.IsNullOrEmpty(strIDs))
                        p.RecieveClientIDs = LitJson.JsonMapper.ToObject<List<int>>(strIDs);

                    int returnMessageLenth = BitConverter.ToInt32(data, 24 + recieveIDsLength);
                    p.RetrunMessage = Encoding.UTF8.GetString(data, 28 + recieveIDsLength, returnMessageLenth);

                    string dataStr = Encoding.UTF8.GetString(data, 28 + recieveIDsLength + returnMessageLenth, count - 24 - recieveIDsLength - returnMessageLenth);
                    p.DataObject = dataStr;
                    processDataCallback?.Invoke(p);
                    Array.Copy(data, count + 4, data, 0, startIndex - 4 - count);
                    startIndex -= (count + 4);
                }
                else
                {
                    break;
                }
            }
            ReSize();//处理完数据后重置缓存区
        }

        public static byte[] ClientPackData(Request packet)
        {
            byte[] packetBytes = BitConverter.GetBytes((int)packet.RequestCode);
            byte[] subCodeBytes = BitConverter.GetBytes((int)packet.RequestSubCode);

            string recieveIds = "";
            if (packet.RecieveClientIDs != null && packet.RecieveClientIDs.Count != 0)
                recieveIds = LitJson.JsonMapper.ToJson(packet.RecieveClientIDs);

            byte[] recieveIdsBytes = Encoding.UTF8.GetBytes(recieveIds);
            byte[] recieveIdsLengthBytes = BitConverter.GetBytes(recieveIdsBytes.Length);

            byte[] dataBytes = Encoding.UTF8.GetBytes(packet.DataStr);

            int dataAmount = 8 + 4 + recieveIdsBytes.Length + dataBytes.Length;

            byte[] dataAmountBytes = BitConverter.GetBytes(dataAmount);

            byte[] newBytes = new byte[dataAmount + 4];

            int index = 0;
            dataAmountBytes.CopyTo(newBytes, index);
            index += dataAmountBytes.Length;

            packetBytes.CopyTo(newBytes, index);
            index += packetBytes.Length;

            subCodeBytes.CopyTo(newBytes, index);
            index += subCodeBytes.Length;

            recieveIdsLengthBytes.CopyTo(newBytes, index);
            index += recieveIdsLengthBytes.Length;

            recieveIdsBytes.CopyTo(newBytes, index);
            index += recieveIdsBytes.Length;

            dataBytes.CopyTo(newBytes, index);

            return newBytes;
        }


        public static byte[] ServerPackData(Response packet)
        {
            //if (packet == null) return null;

            byte[] packetBytes = BitConverter.GetBytes((int)packet.ResponseCode);
            byte[] subCodeBytes = BitConverter.GetBytes((int)packet.ResponseSubCode);
            byte[] returnCodeBytes = BitConverter.GetBytes((int)packet.ReturnCode);

            byte[] requestId = BitConverter.GetBytes(packet.RequestClientID);

            string recieveIds = "";
            if (packet.RecieveClientIDs != null && packet.RecieveClientIDs.Count != 0)
                recieveIds = LitJson.JsonMapper.ToJson(packet.RecieveClientIDs);

            byte[] recieveIdsBytes = Encoding.UTF8.GetBytes(recieveIds);
            byte[] recieveIdsLengthBytes = BitConverter.GetBytes(recieveIdsBytes.Length);


            byte[] returnMessageBytes = Encoding.UTF8.GetBytes(packet.RetrunMessage);

            byte[] returnMessageLengthBytes = BitConverter.GetBytes(returnMessageBytes.Length);

            byte[] dataBytes = Encoding.UTF8.GetBytes(packet.DataStr);

            int dataAmount = packetBytes.Length + subCodeBytes.Length + returnCodeBytes.Length
               + requestId.Length + recieveIdsLengthBytes.Length + recieveIdsBytes.Length
               + returnMessageLengthBytes.Length + returnMessageBytes.Length + dataBytes.Length;

            byte[] dataAmountBytes = BitConverter.GetBytes(dataAmount);

            byte[] newBytes = new byte[dataAmount + 4];

            int index = 0;
            dataAmountBytes.CopyTo(newBytes, index);
            index += dataAmountBytes.Length;

            packetBytes.CopyTo(newBytes, index);
            index += packetBytes.Length;

            subCodeBytes.CopyTo(newBytes, index);
            index += subCodeBytes.Length;

            returnCodeBytes.CopyTo(newBytes, index);
            index += returnCodeBytes.Length;

            requestId.CopyTo(newBytes, index);
            index += requestId.Length;

            recieveIdsLengthBytes.CopyTo(newBytes, index);
            index += recieveIdsLengthBytes.Length;

            recieveIdsBytes.CopyTo(newBytes, index);
            index += recieveIdsBytes.Length;

            returnMessageLengthBytes.CopyTo(newBytes, index);
            index += returnMessageLengthBytes.Length;

            returnMessageBytes.CopyTo(newBytes, index);
            index += returnMessageBytes.Length;

            dataBytes.CopyTo(newBytes, index);

            return newBytes;
        }

        /// <summary>
        /// 重设缓存区
        /// </summary>
        private void ReSize()
        {
            int sub = 0; //相差数
            if (RemainSize > 1024)//一直保持预留缓存空间小于 1024
            {
                int len = RemainSize;
                while (len > 1024)//恢复到1024
                {
                    len -= 1024;
                }
                sub = len - RemainSize;
            }
            else if (RemainSize == 0)//如果没有缓存空间，就自动增加1024
            {
                sub = 1024;
            }

            if (sub != 0)
            {
                byte[] newBytes = new byte[data.Length + sub];//重置后的缓存区大小

                // int useLen = 0;//旧的缓存区和新的缓冲区的 两个之间最小的 那个的长度
                //if (sub > 0)
                //    useLen = data.Length;
                //else
                //    useLen = newBytes.Length;

                int len = Math.Min(data.Length, newBytes.Length);
                Array.Copy(data, 0, newBytes, 0, len);//将数据拷贝到新的缓存区
                data = newBytes;
            }

        }
    }
}
